<?php
/**
 * Created by Mr.Lee.
 * User: mr.lee
 * Date: 2017/7/1
 * Time: 下午6:14
 */

namespace app\common\controller;

use app\common\model\Agent;
use app\common\model\AgentSales;
use app\common\model\AgentSys;
use app\common\model\CardGeneral;
use app\common\model\CardGift;
use app\common\model\CardMember;
use app\common\model\LoginUsers;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\WxOpen;
use think\Config;
use think\Controller;
use think\Session;
use thinkcms\auth\Auth;
use PHPExcel_IOFactory;
use PHPExcel;

class AdminBase extends Controller
{

    public function __construct()
    {
        //cardustest/cardinfo/   cardustest/   Cardusextend
        parent::__construct();
        $auth = new Auth();
        $auth->noNeedCheckRules = [
            'merchant/microprogram/index', 'merchant/microprogram/set_xcx_domain', 'merchant/microprogram/setwebviewdomain',
            'merchant/microprogram/getqrcode', 'merchant/microprogram/get_category', 'merchant/microprogram/get_page',
            'merchant/microprogram/set_prostore', 'merchant/microprogram/bind_tester', 'merchant/microprogram/unbindtester',
            'merchant/microprogram/get_card_id', 'merchant/microprogram/sub_program', 'merchant/microprogram/sub_program_sh',
            'merchant/microprogram/xcx_uncode', 'merchant/microprogram/tpl_ku', 'merchant/microprogram/tpl_add',
            'merchant/microprogram/xcx_getauditstatus', 'merchant/microprogram/setappsecret', 'merchant/microprogram/yylist',
            'merchant/microprogram/set_xcx_search', 'merchant/microprogram/xcx_release', 'merchant/microprogram/options2',
            'merchant/wxsystem/getwxmenu', 'merchant/marke/getusedlink', 'merchant/marke/getusedevent',
             'merchant/store/getIpWsLocation', 'merchant/mach/getmerchs',
            'merchant/marketest/firegive', 'merchant/mach/getmomerchs', 'merchant/uploads/uploadali',
            'merchant/testcardus/getlist', 'merchant/wxsystem/set_xcx_domain', 'merchant/marke/getpaycard', 'merchant/paytest/reportform',
            'merchant/stati/index', 'merchant/hello/fire', 'merchant/wxsystem/gettpllist', 'wxsystemtest/wx_menu',
            //礼品卡
            'merchant/cardgifts/creatcardgift', 'merchant/cardgifts/cardgiftlist', 'merchant/cardgifts/getqrcode',
            'merchant/cardgifts/creatcardrack', 'merchant/cardgifts/cardgiftinfo', 'merchant/cardgifts/getcardgiftinfo',
            'merchant/cardgifts/cardgiftracklist', 'merchant/cardgifts/creatcardrack', 'merchant/cardgifts/machpaygift',
            'merchant/cardgifts/getcardgiftlist', 'merchant/cardgifts/cardgiftrackcate', 'merchant/cardgifts/cardgiftrackthemelist',
            'merchant/cardgifts/cardgiftrackthemeadd', 'merchant/cardgifts/cardgiftrackthemeedit',
            'merchant/cardgifts/getcardrack', 'merchant/cardgifts/getcardrackcate', 'merchant/cardgifts/getgiftrackthemelist',
            'merchant/cardgifts/getgiftracklist', 'merchant/cardgifts/cardgiftrackthemedel', 'merchant/cardgifts/cardrackput',
            'merchant/cardgifts/bindingmicro', 'merchant/cardgifts/uploadmicrocode', 'merchant/cardgifts/consumegift',
            'merchant/cardgifts/delcardgift', 'merchant/cardgifts/consumecardgiftlist','merchant/cardusextend/getbonusbizput',
            'merchant/cardusextend/cardusbizadd','merchant/cardusextend/cardusbizqrcode','merchant/cardusextend/cardusbizcreate',
            'merchant/cardusextend/getbizqrcode',
            //会员卡测试
//            'merchant/cardustest/bonusbizcardsadd', 'merchant/cardustest/sendbonusbizcard','merchant/cardustest/getlists','merchant/cardustest/cardinfo',
//            'merchant/reporttest/reportcardmemberlist',
//            'merchant/reporttest/cardsurvey', 'merchant/reporttest/cardbonuslist', 'merchant/reporttest/carddellist', 'merchant/reporttest/cardoperlog',

            //卡券测试
//            'merchant/reporttest/reportcardgenerallist', 'merchant/cardstest/cardgetlists','merchant/reporttest/reportcardgeneral',
            //momach
            'agent/momach/getipwslocation','agent/momach/getsubcate','agent/momach/machtobank', 'merchant/mach/getsubcate','agent/momach/manager',
            'agent/wxsystem/getwxmenu','agent/momach/getmomerchs',
            //shop
//            'merchant/shoptest/catelist','merchant/shoptest/cateadd','merchant/shoptest/cateedit','merchant/shoptest/cateinfo','merchant/shoptest/catedel',
            //machtest测试
            'merchant/machtest/machlist',


        ];
        $auth->log = true;                 // v1.1版本  日志开关默认true
        $user = $auth::is_login();
        if ($user) {//用户登录状态
            $this->uid = $user['uid'];

            if (!$auth->auth()) {
                die("<script type='text/javascript'>alert('您没有权限访问该模块');history.back(1);</script>");
            }
        } else {
            $this->redirect('Login/index');
        }
        $is_top = Session::get('login_top_mid');
        if (empty($is_top)) {
            $Merchant = new Merchant();
            $log_mid = Session::get('login_mid');
            $top_mid = $Merchant->where('id', $log_mid)->value('top_mid');
            Session::set('login_top_mid', $top_mid);
        }


        if (!Session::has('cp.cpsysname') || !Session::has('cp.copyright') || !Session::has('cp.cpurl')) {
            if (Session::has('sysloginid')) {
                $ss = $this->getcopyrightsys(Session::get('sysloginid'));

            } elseif (Session::has('agentloginid')) {

                $ss = $this->getcopyright(Session::get('agentloginid'));

            } else {

                $ss = $this->getcopyright($this->getagent());


            }


        }
        $level = Session::get('level');
        $level2 = Session::get('level2');
        $modular = request()->module();
        switch ($modular) {
            case "merchant":
                if ($level == "3001" || $level == "3002" || $level == "3003" || $level == "3004" || $level == '0') {

                } else {
                    die("<script type='text/javascript'>alert('您没有权限访问该模块11');history.back(1);</script>");
                }
                break;
            case "leader":
                if ($level == "1001" || $level == "1002" || $level == '0' || $level == '1010') {
                } else {
                    die("<script type='text/javascript'>alert('您没有权限访问该模块11');history.back(1);</script>");
                }
                break;
            case "agent":
                if ($level == "2001" || $level == "2002" || $level == '0') {
                } else {
                    if ($level2 !== "2001") {
                        die("<script type='text/javascript'>alert('您没有权限访问该模块11');history.back(1);</script>");
                    }
                }
                break;
        }
        //输出系统设置


    }

    public function getagentlist()
    {

        $Agent = new Agent();
        if (Session::get('user.uid') == 1) {
            $map = [];
        } else {
            $map['sysid'] = Session::get('sysloginid');
        }
        $list = $Agent->where($map)->field('id')->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $id[] = $v['id'];
            }
            $sid = implode(',', $id);
        } else {
            $sid = "";
        }
        return $sid;

    }

    public function get_agent_id()
    {
        $map['uid'] = Session::get('user.uid');
        $agentid = Agent::where($map)->value('id');
        return $agentid;


    }

    public function get_mer_mid()
    {
        $level2 = Session::get('level2');
        $get_mer_mid = Session::get('get_mer_mid');
        if ($get_mer_mid) {
            $mid = $get_mer_mid;
        } else {
            $mid = '';
            if (empty($level2)) {
                $LoginUsers = new LoginUsers();
                $login_mid = Session::get('login_mid');
                $login_top_mid = Session::get('login_top_mid');
                $user = $LoginUsers->where(['id' => Session::get('user.uid')])->find();
                if ($user['level'] == '3001') {
                    $Merchant = new Merchant();
                    $midlist = $Merchant->where(['top_mid' => $login_top_mid])->field('id')->select();
                    $smid = [];
                    foreach ($midlist as $k => $v) {
                        $smid[] = $v['id'];
                    }
                    $mid = implode(',', $smid);
                    Session::set('get_mer_id', $mid);

                } elseif ($user['level'] == '3002' || $user['level'] == '3003' || $user['level'] == '3004') {
                    $mid = $LoginUsers->where(['id' => Session::get('user.uid')])->value('mid');
                    Session::set('get_mer_id', $mid);

                } elseif ($user['level'] == '2001') {
                    $Agent = new Agent();
                    $mas['agent'] = $Agent->where('uid', $user['id'])->value('id');
                    $Merchant = new Merchant();
                    $mids = $Merchant->where($mas)->field('id')->select();
                    $smid = [];
                    foreach ($mids as $k => $v) {
                        $smid[] = $v['id'];
                    }
                    $mid = implode(',', $smid);
                    Session::set('get_mer_id', $mid);

                } elseif ($user['level'] == '2002') {
                    $AgentSales = new AgentSales();
                    $mas['salesman'] = $AgentSales->where('uid', $user['id'])->value('id');
                    $Merchant = new Merchant();
                    $mids = $Merchant->where($mas)->field('id')->select();
                    $smid = [];
                    foreach ($mids as $k => $v) {
                        $smid[] = $v['id'];
                    }
                    $mid = implode(',', $smid);
                    Session::set('get_mer_id', $mid);

                }
            } else {
                $Merchant = new Merchant();
                $midlist = $Merchant->where(['top_mid' => Session::get('login_top_mid')])->field('id')->select();
                $smid = [];
                foreach ($midlist as $k => $v) {
                    $smid[] = $v['id'];
                }
                $mid = implode(',', $smid);
                Session::set('get_mer_id', $mid);
            }
        }
        return $mid;
    }

    //获取门店数量
    public function get_mid_num()
    {
        $mid = $this->get_mer_mid();
        $mids = explode(',', $mid);
        $num = count($mids);
        return $num;
    }

    public function get_qx_mid($mid)
    {
        $smid = $this->get_mer_mid();
        $arr_mid = explode(',', $smid);
        $isin = in_array($mid, $arr_mid);
        if ($isin) {
            return true;
        } else {
            return false;
        }


    }

    public function getagent($mid = "", $agentid = "")
    {
        if ($agentid) {
            $agent = $agentid;

        } else {
            if ($mid) {
                $Merchant = new Merchant();
                $agent = $Merchant->where('id', $mid)->value('agent');

            } else {
                $top_mid = Session::get('login_top_mid');
                $Momerchant = new Momerchant();
                $agent = $Momerchant->where('id', $top_mid)->value('agent');

            }
        }
        return $agent;
    }

    public function getcopyright($agentid)
    {

        $map['id'] = $agentid;
        $agent = new Agent();
        $info = $agent->where($map)->field('cpsysname,copyright,cpurl,sysid,client_bs')->find();
        if (!empty($info['cpsysname']) && !empty($info['copyright']) && !empty($info['cpurl'])) {
            $wx['cpsysname'] = $info['cpsysname'];
            $wx['copyright'] = $info['copyright'];
            $wx['cpurl'] = $info['cpurl'];

        } else {

            $mab['id'] = $info['sysid'];
            $AgentSys = new AgentSys();
            $info2 = $AgentSys->where($mab)->field('cpsysname,copyright,cpurl')->find();
            if (empty($info2['cpsysname']) && empty($info2['copyright']) && empty($info2['cpurl'])) {

                $wx['cpsysname'] = Config::get('webconfig.copyright_brand');
                $wx['copyright'] = Config::get('webconfig.copyright_name');
                $wx['cpurl'] = Config::get('webconfig.copyright_url');
            } else {

                $wx['cpsysname'] = $info2['cpsysname'];
                $wx['copyright'] = $info2['copyright'];
                $wx['cpurl'] = $info2['cpurl'];
            }

        }
        if ($info['client_bs']) {
            $wx['client_bs'] = $info['client_bs'] . "/";
        } else {
            $wx['client_bs'] = "";
        }
        Session::set('cp.cpsysname', $wx['cpsysname']);
        Session::set('cp.copyright', $wx['copyright']);
        Session::set('cp.cpurl', $wx['cpurl']);
        Session::set('cp.client_bs', $wx['client_bs']);

    }

    public function getcopyrightsys($sysid)
    {

        $map['id'] = $sysid;
        $agent = new AgentSys();
        $info = $agent->where($map)->field('cpsysname,copyright,cpurl')->find();

//        return $info->getLastSql();
        if (empty($info['cpsysname']) && empty($info['copyright']) && empty($info['cpurl'])) {
            $wx['cpsysname'] = Config::get('webconfig.copyright_brand');
            $wx['copyright'] = Config::get('webconfig.copyright_name');
            $wx['cpurl'] = Config::get('webconfig.copyright_url');
        } else {

            $wx['cpsysname'] = $info['cpsysname'];
            $wx['copyright'] = $info['copyright'];
            $wx['cpurl'] = $info['cpurl'];
        }
        Session::set('cp.cpsysname', $wx['cpsysname']);
        Session::set('cp.copyright', $wx['copyright']);
        Session::set('cp.cpurl', $wx['cpurl']);


    }

    //获取授权状态
    public function get_auth_type($mid = '')
    {
//        if (empty($mid)){
//            $Momerchant = new Momerchant();
//            $top_mid = Session::get('login_top_mid');
//            $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id');
//            if ($wx_open_id){
//                $res = 1;
//            }else{
//                $res = 0;
//            }
//        }else {
        if ($mid) {
            $Merchant = new Merchant();
            $wx_open_id = $Merchant->where('id', $mid)->value('wx_open_id');

        } else {
            $top_mid = Session::get('login_top_mid');
            $Momerchant = new Momerchant();
            $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id');
//           return $wx_open_id;
        }
//            if ($wx_open_id){
//                $res = 1;
//            }else{
//                $res = 0;
//            }
//        }

        return $wx_open_id;
    }


    public function loads($file, $title, $colum = 3)
    {
        $code = [];
        $filetype = PHPExcel_IOFactory::identify($file);
        $excelread = PHPExcel_IOFactory::createReader($filetype);
        //加载文件

        $phpexcel = $excelread->load($file);
        $sheet = $phpexcel->getSheet(0);
        $column = $sheet->getHighestColumn();
        //获取当前工作表的行数
        $rows = $sheet->getHighestRow();
//把字母列转换成数字，这里获取的是列的数，并且列的索引
        $columns = \PHPExcel_Cell::columnIndexFromString($column);
        $arr = [];
        //创建一个表头数组，个数与列数一致
//通过循环把表格中读取到的数据，存入二维数据，以便后期数据库的写入操作，行是从1开始的
        for ($i = $colum; $i <= $rows; $i++) {
            $arr_col = [];
            //列是从0开始的
            for ($col = 0; $col < $columns; $col++) {
                //把数字列转换成字母列，这里是通的列索引获取到对应的字母列
                $columnname = \PHPExcel_Cell::stringFromColumnIndex($col);
                $arr_col[$title[$col]] = $sheet->getCell($columnname . $i)->getValue();

            }

            $arr[] = $arr_col;
        }
        $arrs = $this->get_arr($arr);


        return $arrs;

//        }

    }

    //检查mid 是否数据top_mid
    public function checkmid($mid)
    {
        $Merchant = new Merchant();
        $map['id'] = $mid;
        $map['top_mid'] = Session::get('login_top_mid');
        $is = $Merchant->where($map)->value('id');
        if ($is) {
            $res = true;
        } else {
            $res = false;
        }
        return $res;
    }

    //检查mid 是否数据top_mid
    public function checkcardid($card_id)
    {
        $CardGeneral = new CardGeneral();
        $CardMember = new CardMember();
        $CardGift = new CardGift();
        $map['card_id'] = $card_id;
        $map['top_mid'] = Session::get('login_top_mid');
        $is = $CardGeneral->where($map)->value('id');
        if ($is) {
            $res = true;
        } else {
            $is = $CardMember->where($map)->value('id');
            if ($is) {
                $res = true;
            } else {
                $is = $CardGift->where($map)->value('id');
                if ($is) {
                    $res = true;
                } else {
                    $res = false;
                }
            }
        }
        return $res;
    }

    public function getExcel($fileName, $data, $sheetname, $nums, $title)
    {
        // 对数据进行检验
        if (empty($data) || !is_array($data)) {
            die("data must be a array");
        }
        $date = date("Y_m_d", time());
        $fileName .= "_{$date}.xls";
        // 创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new PHPExcel();
        $objProps = $objPHPExcel->getProperties();


        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();

        $objPHPExcel->getActiveSheet()
            ->getStyle()
            ->getFont()
            ->setName('微软雅黑'); // 设置字体
        $objPHPExcel->getActiveSheet()
            ->getDefaultRowDimension()
            ->setRowHeight(15); // 设置默认高度

        // $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth('5');//设置列宽
        // $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth('22');//设置列宽
        // $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth('22');//设置列宽
        // $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth('22');//设置列宽
        // $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth('22');//设置列宽
        // $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth('22');//设置列宽
        // $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth('40');//设置列宽

        // 设置边框
        $sharedStyle1 = new \PHPExcel_Style();
        $sharedStyle1->applyFromArray(array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        ));
        $objPHPExcel->getActiveSheet()->mergeCells($nums);
        $snum = explode(':', $nums);
        $objActSheet->setCellValue($snum[0], $title);
        $objActSheet->getStyle($snum[0])->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet->getStyle($snum[0])->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objActSheet->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objActSheet->getStyle($snum[0])->getFont()->setName('宋体');
        $objActSheet->getRowDimension(1)->setRowHeight(50);
        $objActSheet->getStyle($snum[0])->getFont()->setSize(20);

        foreach ($data as $ke => $row) {

            foreach ($row as $key => $rows) {

//                   if($ke==0){
////                if ($rows['1'] == '字段') {
//                    $rows[0] = 'ID';}
                // 背景色填充
                // $objPHPExcel->getActiveSheet()->getStyle("A{$column}:J{$column}")->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
                // $objPHPExcel->getActiveSheet()->getStyle("A{$column}:J{$column}")->getFill()->getStartColor()->setARGB('FF4F81BD');
//                }

                $objPHPExcel->getActiveSheet()
                    ->getStyle("A{$column}:J{$column}")
                    ->getAlignment()
                    ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); // 垂直居中
                $objPHPExcel->getActiveSheet()
                    ->getStyle("A{$column}:J{$column}")
                    ->getAlignment()
                    ->setWrapText(true); // 换行
                // 行写入
                $span = ord("A");
                $span2 = ord("@");


                foreach ($rows as $keyName => $value) {
                    // 列写入
                    if ($span > ord("Z")) {
                        $span2 += 1;
                        $span = ord("A");
                        $j = chr($span2) . chr($span); // 超过26个字母时才会启用
                    } else {
                        if ($span2 >= ord("A")) {
                            $j = chr($span2) . chr($span); // 超过26个字母时才会启用
                        } else {
                            $j = chr($span);
                        }
                    };


                    if (preg_match("/^[0-9]+$/", $value) && strlen($value) > 10) {

                        $objActSheet->setCellValue($j . $column, "'" . $value);
                    } else {
                        $objActSheet->setCellValue($j . $column, $value);
                    }

                    $span++;
                }
                $column++;
            }
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        // 设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->getActiveSheet()->setTitle($sheetname);
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); // 文件通过浏览器下载
        exit();

    }

    private function get_arr($arr)
    {
        foreach ($arr as $k => $v) {
            if (is_array($arr[$k])) {
                $arr[$k] = $this->get_arr($arr[$k]);
            } else {
                if (empty($arr[$k])) {
                    unset($arr[$k]);
                }
            }
        }
        foreach ($arr as $k => $v) {
            if (empty($v)) {
                unset($arr[$k]);
            }

        }
        return $arr;
    }

    public function getsysoem_mid($sysid)
    {
//        $Agent = new Agent();
//        $agentlist = $Agent->where(array('sysid' => $sysid))->field('id')->select();
//        foreach ($agentlist as $k => $v) {
//            $agent[] = $v['id'];
//        }
//        $agentall = implode(',', $agent);
        $Merchant = new Merchant();
        $map['agent'] = $this->getagentlist();
        $mids = $Merchant->where($map)->field('id')->select();
        if ($mids) {
            foreach ($mids as $k => $v) {
                $mid2[] = $v['id'];
            }
            $mid = implode(',', $mid2);
        } else {
            $mid = "";
        }
        return $mid;


    }

    //获取有权限的门店列表
    public function getmchlist()
    {
//        Session::set('getmchlist', "");
        //有权限的门店列表
        $getmchlist = Session::get('getmchlist');
        if ($getmchlist) {
            $info = $getmchlist;
        } else {
            $map['id'] = ['in', $this->get_mer_mid()];
            $Merchant = new Merchant();
            $list = $Merchant->where($map)->field('id as mid,merchant as merchant')->select();
            $info = json_encode($list,JSON_UNESCAPED_UNICODE);
            Session::set('getmchlist', $info);


        }

        return $info;
    }
    //获取门店名称
    public function getmchname_mch($mid){
        $map['id']=['in',$mid];
        $Merchant=new Merchant();
        $list=$Merchant->where($map)->field('merchant')->select();
        foreach($list as $k=>$v){
            $list2[]=$v['merchant'];
        }
        $info=implode(",",$list2);
        return $info;

    }

    //获取会员卡ID
    public function get_cardus_id(){
        $card_id = Session::get('mach_cardus_id');
        if (!$card_id) {
            $CardMember = new CardMember();
            $map['top_mid'] = Session::get('login_top_mid');
            $card_id = $CardMember->where($map)->value('card_id');
            if ($card_id) {
                Session::set('mach_cardus_id', $card_id);
            }
        }
        return $card_id;
    }
    //获取代理商url
//    public function getagenturl(){
//        $Momerchant = new Momerchant();
//        $Agent=new Agent();
//        $top_mid = Session::get('login_top_mid');
//        $agent_id = $Momerchant->where('id', $top_mid)->value('agent');
//        $agent_url = $Agent->where(['id'=>$agent_id])->value('open_url');
//        return 'https://'.$agent_url;
//    }

}